<?php

/**
 * @package NUKEVIET
 * @subpackage WikiDic Service
 * @author Long Nguyen (long@wpvampire.com)
 * @copyright 2011
 * @since 3.2
 */

if ( ! defined( 'NV_ADMIN' ) or ! defined( 'NV_MAINFILE' ) or ! defined( 'NV_IS_MODADMIN' ) ) die( 'Stop!!!' ); 

require_once(NV_ROOTDIR . "/modules/" . $module_name . '/libs/functions.php');
require_once(NV_ROOTDIR . "/modules/" . $module_name . '/libs/formatting.php');

/**
 * generates html select dropdown list with options
 * if values is two dimensional then adds optgroup too
 * 
 * @link http://snippets.dzone.com/posts/show/2572
 * @param 	string	$name			selectbox name and id
 * @param 	array		$values		options
 * @param 	mixed		$selected	selected option
 * @param 	array		$attributes additonal attributes
 *
 * @return 	string	html source with selectbox
 */
function html_selectbox($name, $values, $selected=NULL, $attributes=array())
{
	$attr_html = '';
	if(is_array($attributes) && !empty($attributes))
	{
		foreach ($attributes as $k=>$v)
		{
			$attr_html .= ' '.$k.'="'.$v.'"';
		}
	}

	$output = '<select name="'.$name.'" id="'.$name.'"'.$attr_html.'>'."\n";
	if(is_array($values) && !empty($values))
	{
		foreach($values as $key=>$value)
		{
			if(is_array($value))
			{
				$output .= '<optgroup label="'.$key.'">'."\n";
				foreach($value as $k=>$v)
				{
					$sel = $selected==$k ? ' selected="selected"' : '';
					$output .= '<option value="'.$k.'"'.$sel.'>'.$v.'</option>'."\n";
				}
				$output .= '</optgroup>'."\n";
			}
			else
			{
				$sel = $selected==$key ? ' selected="selected"' : '';
				$output .= '<option value="'.$key.'"'.$sel.'>'.$value.'</option>'."\n";
			}
		}
	}
	$output .= "</select>\n";

	return $output;
}

/**
 *
 * @link http://icodesnip.com/snippet/php/php-convert-array-to-object-with-stdclass
 */
function array2object($array) {
    if(!is_array($array)) {
        return $array;
    }
     
    $object = new stdClass();
    if (is_array($array) && count($array) > 0) {
      foreach ($array as $name=>$value) {
         $name = strtolower(trim($name));
         if (!empty($name)) {
            $object->$name = array2object($value);
         }
      }
      return $object;
    }
    else {
      return FALSE;
    }
}

/**
 *
 * @link http://codex.wordpress.org/Function_Reference/get_users
 */
function get_users($args = array())
{
	global $db;
	
	$default_args = array(
		'field_key' => '',
		'field_value' => '',
		'field_compare' => '=',
		'orderby' => 'userid',
		'order' => 'ASC',
	);
	
	$args = wp_parse_args( $args, $default_args);
	
	$query = "SELECT * FROM `" . NV_USERS_GLOBALTABLE . "`";
	if ( ! empty($args['field_key']) ) {
		$query .= " WHERE `". $args['field_key'] . "` " . $args['field_compare'] . " '" . $args['field_value'] . "'";
	}
	$query .= " ORDER BY `". $args['orderby'] . "` " . $args['order'];
	$result = $db->sql_query($query); 
	$users = false;
	while ($user = $db->sql_fetch_assoc()) {
		$user = array2object($user);
		$users[] = $user;
	}
	return $users;
}

?>